const app = getApp();
// 初始化动画实例
let animation = wx.createAnimation({
  duration: 400,
  timingFunction: "linear",
  delay: 0
});
Page({
  data: {
    scollTop: 0,
    scroll_into_view: 'foodtype0', // scroll-view的初始位置
    showModalStatus: false, //是否弹窗
    seriesArray: [], // 导航的数组，通过ajax获取
    foodArray: [], // 食品的对象数组
    shoppingList: [], // 购物车储存的对象数组
    totalPrice: 0, // 购物车的总价格
    totalCount: 0, // 购物车的总数量
    movelength: 0, // 上移或下拉动画的单位距离
    cartIsHidden: true, // 购物车是否隐藏
    cartIndexIsHidden: true, // 购物车详情菜单是否隐藏
    animationData: {}, // 动画动作对象
    shareCode: "", //邀请码
    input_sharecode: "", //输入的邀请码
    ifShareCode: false
  },
  // 设置标题名
  onReady: function() {
    wx.setNavigationBarTitle({
      title: '菜单'
    })
  },
  // 加载ajax的最佳时机
  onLoad: function(options) {
    let that = this
    that.getDishesSeries();
    that.getDishes();
    that.getCart();
  },
  onShow: function(options) {
    let that = this

    // console.log(this.data);
    // console.log('onshow');
    setInterval(function() {
      that.getCart();
      // console.log(2);
    }, 1000)
    this.onLoad();
  },
  // 跳页的id
  changepage: function(e) {
    // 滚动到指定的id
    let goPage = e.currentTarget.id

    this.setData({
      scroll_into_view: "foodtype" + goPage
    })
  },
  // 点击‘+’添加进购物车
  addShopcart: function(e) {
    var dishesid = e.currentTarget.dataset.dishesid;
    let move_length = this.data.movelength;
    let shopping_list = this.data.shoppingList;
    let total_price = this.data.totalPrice;
    let total_count = this.data.totalCount + 1;
    total_price = parseFloat(total_price) + parseFloat(e.target.dataset.price);
    let itemNum = 1;
    let that = this;

    // 是否有同种商品判断
    if (this.data.shoppingList.length > 0) {
      // 商品名是否相同判断，不重复添加同名商品
      let isHave = this.data.shoppingList.findIndex(item => item.name == e.target.dataset.name)
      if (isHave != -1) {
        that.data.shoppingList[isHave].num++
          var dishesNum = that.data.shoppingList[isHave].num;
        this.updateCart(dishesid, dishesNum); //更新购物车项
      } else {
        // 购物车数组加进新的一样食品
        that.postCart(dishesid); //添加新购物车项
        that.data.shoppingList.push({
          price: e.currentTarget.dataset.price,
          name: e.currentTarget.dataset.name,
          dishesid: e.currentTarget.dataset.dishesid,
          num: itemNum
        })
        // 动画效果的长度添加
        move_length++
      }
      // 没有商品时直接添加
    } else {
      that.postCart(dishesid); //添加新购物车项
      this.data.shoppingList.push({
        price: e.currentTarget.dataset.price,
        name: e.currentTarget.dataset.name,
        dishesid: e.currentTarget.dataset.dishesid,
        num: itemNum
      })
      move_length++
    }
    // 动画上拉长度对应的bottom的计算
    /**
     *  mlength是bottom的长度
     *  animation.bottom(mlength).step() 加入动画队列
     */
    let mlength = move_length * 55;
    if (move_length > 1) {
      mlength = 55 + (move_length - 1) * 65;
    }
    this.animation = animation
    animation.bottom(mlength).step()
    this.setData({
      animationData: animation.export()
    })
    this.setData({
      shoppingList: shopping_list,
      totalPrice: total_price,
      totalCount: total_count,
      // 购物车当有商品时弹出
      cartIsHidden: false,
      movelength: move_length
    })
  },

  // 购物车详情抽屉点击时弹出
  showCart: function(e) {
    let move_length = 0;
    move_length = this.data.movelength * 55;
    if (this.data.movelength > 1) {
      move_length = 55 + (this.data.movelength - 1) * 65;
    }
    this.animation = animation
    animation.bottom(move_length).step()
    let cart_indexIsHidden = !this.data.cartIndexIsHidden;
    this.setData({
      cartIndexIsHidden: cart_indexIsHidden,
      animationData: animation.export()
    })
  },

  // 购物车详情抽屉中增加数量
  addShopcartInCart: function(e) {
    var dishesid = e.currentTarget.dataset.dishesid;
    let total_count = this.data.totalCount + 1;
    let addTarget = this.data.shoppingList.findIndex(item => item.name === e.target.dataset.name);
    this.data.shoppingList[addTarget].num++;
    let tempPrice = parseFloat(this.data.totalPrice) + parseFloat(this.data.shoppingList[addTarget].price)
    this.setData({
      shoppingList: this.data.shoppingList,
      totalPrice: tempPrice,
      totalCount: total_count
    })

    this.updateCart(dishesid, this.data.shoppingList[addTarget].num);
  },
  // 购物车详情抽屉中减少数量,但没有商品时需要抽屉下降并购物车组件消失
  deleteShopcartInCart: function(e) {
    let dishesid = e.currentTarget.dataset.dishesid;
    let move_length = this.data.movelength;
    // 选定被点击的元素
    let addTarget = this.data.shoppingList.findIndex(item => item.name === e.target.dataset.name);
    let tempPrice = 0;
    let total_count = this.data.totalCount - 1;
    this.data.shoppingList[addTarget].num--;
    var dishesNum = this.data.shoppingList[addTarget].num;

    //后台交互
    if (dishesNum < 1) { //delete
      this.deleteCart(dishesid);
    } else { //update
      this.updateCart(dishesid, dishesNum);
    }
    //界面的修改
    if (this.data.shoppingList[addTarget].num < 1) {
      // 总价的减少
      tempPrice = parseFloat(this.data.totalPrice) - parseFloat(this.data.shoppingList[addTarget].price)
      this.data.shoppingList.splice(addTarget, 1);
      move_length--;
      // bottom值变化产生动画
      let mlength = move_length * 61;
      if (move_length < 2) {
        mlength = move_length * 50
      }
      if (move_length < 1) {
        mlength = -55
      }
      // console.log(this.data.totalPrice)
      this.animation = animation
      animation.bottom(mlength).step()
      // 总数等于0时购物车组件设置为消失
      if (total_count == 0) {
        let cart_isHidden = !this.data.cartIsHidden
        // console.log(cart_isHidden)
        // 这里设置一个计时器，让下拉抽屉动画完成后再消失组件，不然体验性太差
        setTimeout(() => {
          this.setData({
            cartIsHidden: cart_isHidden
          })
        }, 1000)
      }
      this.setData({
        shoppingList: this.data.shoppingList,
        movelength: move_length,
        animationData: animation.export(),
        totalPrice: tempPrice
      })
    } else {
      // 计算出来新的价格
      tempPrice = parseFloat(this.data.totalPrice) - parseFloat(this.data.shoppingList[addTarget].price)
      // console.log(this.data.totalPrice)
    }
    this.setData({
      shoppingList: this.data.shoppingList,
      totalPrice: tempPrice,
      totalCount: total_count
    })
  },
  finishedPay: function() {
    wx.showToast({
      title: '支付成功',
      icon: "success",
      duration: 2000
    })
  },
  getCart: function() { //与后台交互，得到cart项,传入参数，菜的id
    var that = this
    var _url = app.globalData.ip + '/api/shopcart';
    if (this.data.input_sharecode != "" && this.data.input_sharecode != undefined) {
      console.log(this.data.input_sharecode);
      _url = _url + "?shareCode=" + this.data.input_sharecode;
      that.setData({
        ifShareCode: true
      })
    } else {
      that.setData({
        ifShareCode: false
      })
    }
    wx.request({
      url: _url,
      method: 'GET',
      header: {
        "X-Token": app.globalData.token
      },
      success: function(e) {
        that.clearCart();
        console.log("fuck")
        console.log(e)
        var temp = e.data.data;
        var _shoppingList = [];
        var _totalPrice = that.data.totalPrice;
        var _totalCount = that.data.totalCount;
        var _movelength = that.data.movelength;
        var _cartIsHidden = true;
        for (var i = 0; i < temp.length; i++) {
          _shoppingList.push({
            price: temp[i].dish.price,
            name: temp[i].dish.name,
            dishesid: temp[i].dish.id,
            num: temp[i].number
          })
          _totalPrice += (temp[i].dish.price * temp[i].number);
          _totalCount += temp[i].number;
          _movelength++;
          _cartIsHidden = false;
        }
        that.setData({
          shoppingList: _shoppingList,
          totalPrice: _totalPrice,
          totalCount: _totalCount,
          movelength: _movelength,
          cartIsHidden: _cartIsHidden,
        })
      }
    })
  },
  clearCart: function() {
    var _shopcart = this.data.shoppingList;
    for (var i in _shopcart) {
      _shopcart.pop();
    }
    this.setData({
      totalPrice: 0,
      totalCount: 0,
      movelength: 0,
      cartIsHidden: true,
    })
  },
  getDishesName: function(dishesid) {
    wx.request({
      url: app.globalData.ip + '/api/dishes/' + dishesid,
      method: 'GET',
      success: function(e) {
        return e.data.data.name
      }
    })
  },
  getDishesSeries: function() {
    //请求菜类
    var that = this;
    wx.request({
      url: app.globalData.ip + '/api/dishesSeries',
      method: "GET",
      success: function(res) {
        that.setData({
          seriesArray: res.data.data
        })
      }
    })
  },
  getDishes: function() {
    var that = this;
    //根据菜类，请求所有的菜品
    wx.request({
      url: app.globalData.ip + '/api/dishesSeries/dishes',
      method: "GET",
      success: function(res) {
        // console.log(res.data.data)
        var _seriesArray = that.data.seriesArray;
        for (var i = 0; i < _seriesArray.length; i++) {
          var series_name = _seriesArray[i].name;
          _seriesArray[i].dishesArray = res.data.data[series_name];
        }
        that.setData({
          seriesArray: _seriesArray
        })
      }
    })
  },
  postCart: function(dishid) { //与后台交互，提交cart项,传入参数，菜的id
    var that = this;
    var _url = app.globalData.ip + '/api/shopcart';
    if (this.data.input_sharecode != null) {
      _url = _url + "?shareCode=" + this.data.input_sharecode;
      that.setData({
        ifShareCode: true
      })
    }
    wx.request({
      url: _url,
      method: 'POST',
      header: {
        "X-Token": app.globalData.token
      },
      data: {
        dishesId: dishid,
      },
      success: function(e) {

      }
    })
  },
  updateCart: function(dishid, num) { //与后台交互，更新cart项,传入参数，菜的id和菜的数量
    // console.log(dishid, num);
    var that = this;
    var _url = app.globalData.ip + '/api/shopcart';
    if (this.data.input_sharecode != null) {
      _url = _url + "?shareCode=" + this.data.input_sharecode;
      that.setData({
        ifShareCode: true
      })
    }
    wx.request({
      url: _url,
      method: 'PUT',
      header: {
        "X-Token": app.globalData.token
      },
      data: {
        dishesId: dishid,
        number: num,
      },
      success: function(e) {
        // console.log(e)
      }
    })
  },
  deleteCart: function(dishid) { //与后台交互，删除cart项,传入参数，菜的id
    var _url = app.globalData.ip + '/api/shopcart';
    if (this.data.input_sharecode != null) {
      _url = _url + "?shareCode=" + this.data.input_sharecode;
      that.setData({
        ifShareCode: true
      })
    }
    wx.request({
      url: _url,
      method: 'DELETE',
      header: {
        "X-Token": app.globalData.token
      },
      data: {
        dishesId: dishid,
      },
      success: function(e) {

      }
    })
  },
  toConfirmOrder: function(e) { //前往确认订单
    var that = this;
    wx.navigateTo({
      url: '../orderConfirm/orderConfirm?money=' + that.data.totalPrice
    })
  },
  shareOrder: function(e) {
    var that = this;
    wx.request({
      url: app.globalData.ip + '/api/shopcart/share',
      method: "POST",
      header: {
        "X-Token": app.globalData.token
      },
      success: e => {
        // console.log("fuckfuck")
        // console.log(e);
        var _shareCode = e.data.data;
        // console.log(_shareCode);
        that.setData({
          shareCode: _shareCode
        })
        wx.showModal({
          title: '邀请码',
          content: _shareCode + "",
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })

  },
  sharecodeInput: function(e) {
    var that = this;

    that.setData({
      input_sharecode: e.detail.value
    })

    // console.log(that.data.input_sharecode);
  },
  powerDrawer: function(e) {
    var currentStatus = e.currentTarget.dataset.status;
    var that = this;
    that.util(currentStatus);

  },
  util: function(currentStatus) {
    var that = this
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });

    // 第2步：这个动画实例赋给当前的动画实例 
    that.animation = animation;

    // 第3步：执行第一组动画 
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存 
    that.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画 
    setTimeout(function() {
      // 执行第二组动画 
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
      that.setData({
        animationData: animation
      })

      //关闭 
      if (currentStatus == "close") {
        that.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)

    // 显示 
    if (currentStatus == "open") {
      that.setData({
        showModalStatus: true
      });
    }
  },
  gotoDishesDetail: function(e) {
    var _dishesid = e.currentTarget.dataset.dishesid;
    // console.log(e)
    wx.navigateTo({
      url: '../dishesDetail/dishesDetail?dishesid=' + _dishesid,
    })
  }
})